﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data;

using System.Windows.Controls;
using System.Collections.Specialized;


namespace kasy_4
{
    class Control
    {
        Firebird database = new Firebird();
        MainWindow mainWindow = new MainWindow();
        Kasy kasy = new Kasy();
        Document document = new Document();
        Printer printer = new Printer();
        PrintTable printTable = new PrintTable();
        Item item = new Item();
        Session session = new Session();
        private int currentBoxNumber = 1;
        DataTable dataTable = new DataTable();

        StringDictionary warehousemanDict = new StringDictionary();
        StringDictionary documentDict = new StringDictionary();
        
        public Control(MainWindow mw)
        {
            this.mainWindow = mw;
        }

        public void Loaded()
        {
            mainWindow.tabControl1.Items.Remove(mainWindow.tabScann);
            mainWindow.tabControl1.Items.Remove(mainWindow.tabSelectDocument);
            mainWindow.tbLogin.Focus();
            this.Warning();
        }

        public void Login(string login, string passwd)
        {
            try
            {
                session.UserId = login;
                database.Login(login, passwd);
                mainWindow.tabControl1.Items.Add(mainWindow.tabSelectDocument);
                mainWindow.tabControl1.Items.Remove(mainWindow.tabLog);
                mainWindow.pbPasswd.Password = string.Empty;
                this.GetDocuments();
                this.GetWarehouseman();
                mainWindow.cbDocument.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Błąd formatki", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void Logout()
        {
            try
            {
                database.Logout();
                if(!mainWindow.tabControl1.Items.Contains(mainWindow.tabLog))
                    mainWindow.tabControl1.Items.Add(mainWindow.tabLog);
                if (mainWindow.tabControl1.Items.Contains(mainWindow.tabScann))
                    mainWindow.tabControl1.Items.Remove(mainWindow.tabScann);
                if (mainWindow.tabControl1.Items.Contains(mainWindow.tabSelectDocument))
                    mainWindow.tabControl1.Items.Remove(mainWindow.tabSelectDocument);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Błąd logowania do bazy danych", MessageBoxButtons.OK, MessageBoxIcon.Error);
                mainWindow.Focus();
            }
        }

        public void GetDocuments()
        {
            string query = "SELECT p.DOCUMENTID, p.DOCUMENTNAME, p.SHOPID, p.WAREHOUSE FROM KASY_GET_DOCUMENTS('', '') p";
            documentDict=database.GetDictionary(query);
            mainWindow.cbDocument.ItemsSource = new BindingSource(documentDict, null);
        }

        public void GetWarehouseman()
        {
            string query = "SELECT p.LOGIN,p.NAME FROM KASY_GET_WAREHOUSEMAN('') p";
            warehousemanDict = database.GetDictionary(query);
            mainWindow.cbWarehouseman.ItemsSource = new BindingSource(warehousemanDict,null);
        }

        public void OpenDocument()
        {
            try
            {
                if (!string.IsNullOrEmpty(mainWindow.cbDocument.Text) && !string.IsNullOrEmpty(mainWindow.cbWarehouseman.Text))
                {
                    document.DocumentId = mainWindow.cbDocument.SelectedValue.ToString();
                    document.Warehouseman = mainWindow.cbWarehouseman.SelectedValue.ToString();
                    //visual
                    mainWindow.tabControl1.Items.Add(mainWindow.tabScann);
                    mainWindow.tabControl1.Items.Remove(mainWindow.tabSelectDocument);
                    //todo
                    this.GetDocumentInfo();
                    this.ViewDocumentInfo();
                    this.GetDocumentPositions();
                    //
                    mainWindow.cbDocument.Text = string.Empty;
                    mainWindow.cbWarehouseman.Text = string.Empty;
                    mainWindow.tbScaner.Focus();
                }
                else
                {
                    MessageBox.Show("Wybierz dokument i magazyniera, który go kompletował!", "Ważny komunikat", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    mainWindow.tbScaner.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Błąd otwarcia dokumentu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                mainWindow.Focus();
            }
            
        }

        private void GetDocumentInfo()
        {
            try
            {
                string query = String.Format("SELECT p.DOCUMENTNAME, p.QTYALL, p.QTYSCANNED, p.QTYREST, p.QTYBOX,p.PCS_IN_BOX,p.shop_id FROM KASY_DOCUMENT_INFO({0}) p", document.DocumentId);
                dataTable = database.GetData(query, document.DocumentId).Tables[0];
                document.DocumentName = dataTable.Rows[0].ItemArray[0].ToString();
                document.QtyAll = (int)dataTable.Rows[0].ItemArray[1];
                document.QtyScanned = (int)dataTable.Rows[0].ItemArray[2];
                document.QtyRest = (int)dataTable.Rows[0].ItemArray[3];
                document.QtyBox = (int)dataTable.Rows[0].ItemArray[4];
                document.BoxNumber = this.currentBoxNumber;
                document.PcsBox = (int)dataTable.Rows[0].ItemArray[5];
                document.ShopId = dataTable.Rows[0].ItemArray[6].ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("Błąd",ex);
            }
        }

        private void GetDocumentPositions()
        {
            string query = String.Format("SELECT p.NAME, p.INDEKS, p.QTY, p.QTY_SCANNED, p.BOX_NUMBER FROM KASY_GET_POSITIONS({0}) p", document.DocumentId);
            mainWindow.dataGrid1.ItemsSource = new BindingSource(database.GetData(query, document.DocumentId).Tables[0], null);
        }

        private void ViewDocumentInfo()
        {
            mainWindow.lblView1.Content = string.Format("Dokument magazynowy: {0}",document.DocumentName);
            mainWindow.lblView2.Content = string.Format("Dokument zawiera: {0} sztuk", document.QtyAll);
            mainWindow.lblView3.Content = string.Format("Zeskanowano: {0} sztuk", document.QtyScanned);
            mainWindow.lblView4.Content = string.Format("Pozostało : {0} sztuk", document.QtyRest);
            mainWindow.lblView5.Content = string.Format("Bieżący numer kartonu : {0}", document.BoxNumber);
        }

        public void CloseDocument()
        {
            document = new Document();
            if (!mainWindow.tabControl1.Items.Contains(mainWindow.tabSelectDocument) && !mainWindow.tabControl1.Items.Contains(mainWindow.tabLog))
                mainWindow.tabControl1.Items.Add(mainWindow.tabSelectDocument);
            if (mainWindow.tabControl1.Items.Contains(mainWindow.tabScann))
                mainWindow.tabControl1.Items.Remove(mainWindow.tabScann);
            document = new Document();
        }

        public void Scanner()
        {
            item.Barcode=mainWindow.tbScaner.Text;
            mainWindow.tbScaner.Text = string.Empty;
            string query = String.Format("SELECT p.EAN, p.ITEMID, p.ITEMNAME, p.ITEMCOLOR, p.ITEMSIZE FROM KASY_GET_ITEM_INFO({0}) p",item.Barcode);
            this.SetScanItem(document.DocumentId,item.Barcode,document.BoxNumber.ToString());
            DataTable dt = database.GetData(query, document.DocumentId).Tables[0];
            item.Barcode = dt.Rows[0].ItemArray[0].ToString();
            item.ItemId = dt.Rows[0].ItemArray[1].ToString();
            item.ItemName = dt.Rows[0].ItemArray[2].ToString();
            item.ItemColor = dt.Rows[0].ItemArray[3].ToString();
            item.ItemSize = dt.Rows[0].ItemArray[4].ToString();
            this.ViewScanner();
            this.GetDocumentPositions();
            this.GetDocumentInfo();
            this.ViewDocumentInfo();
        }

        private void ViewScanner()
        {
            mainWindow.lblEAN.Content= string.Format("EAN: {0}",item.Barcode);
            mainWindow.lblItem.Content = string.Format("Model: {0}", item.ItemId);
            mainWindow.lblItemName.Content = string.Format("Nazwa: {0}", item.ItemName);
            mainWindow.lblItemColor.Content = string.Format("Kolor: {0}", item.ItemColor);
            mainWindow.lblItemSize.Content = string.Format("Rozmiar: {0}", item.ItemSize);
        }

        public void NewBox()
        {
            string query = string.Format("SELECT p.INDEKS, p.QTY FROM KASY_GET_BOX_ITEMS({0}, {1}) p",document.DocumentId,document.BoxNumber);
            DataSet ds = database.GetData(query, "wydruk");
            //ds.ReadXml("test.xml");
            
            this.PrintTableInit();
            printer.PrintDocument(ds, printTable);
            this.currentBoxNumber++;
            this.ViewDocumentInfo();
            document.BoxNumber = this.currentBoxNumber;
            
        }

        public void Confirm()
        {
            this.CloseDocument();
        }

        public void Warning()
        {
            System.Media.SoundPlayer sp = new System.Media.SoundPlayer("Warning.wav");
            sp.LoadAsync();
            sp.Play();
        }

        private void PrintTableInit()
        {
            printTable.BoxNumber = document.BoxNumber.ToString();
            printTable.AllQty = document.PcsBox.ToString();
            printTable.Cashier = session.UserId;
            printTable.DocumentName = document.DocumentName;
            printTable.ShopName = document.ShopId;
            printTable.Warehouseman = warehousemanDict[document.Warehouseman.ToString()].ToString();
        }

        private void SetScanItem(string documentId, string barcode, string boxNumber)
        {
            string query = string.Format("SELECT p.MESSAGE_RETURN FROM KASY_SCANNER({0}, {1}, {2}) p", barcode, documentId, boxNumber);
            string value = database.SetValue(query);
            if (!value.Contains("OK"))
            {
                Warrning w = new Warrning();
                w.Show();
                this.Warning();
            }
        }

    }
}